package org.rockyang.dike.thymeleaf.processor;

import org.rockyang.dike.core.SubjectManager;
import org.rockyang.dike.utils.AuthorizationUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.List;

/**
 * <dike:hasPermission> 标签解析
 * @author yangjian
 */
public class HasPermissionElementProcessor extends AbstractElementTagProcessor {

    private static final String ELEMENT_NAME = "haspermission";
    private static final int PRECEDENCE = 300;
    private static final String DELIMITER = ",";

    public HasPermissionElementProcessor(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, "haspermission", true, (String)null, false, 300);
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, IElementTagStructureHandler iElementTagStructureHandler) {
        String rawValue = ThymeleafFacade.getRawValue(iProcessableElementTag, "name");
        List values = ThymeleafFacade.evaluateAsStringsWithDelimiter(iTemplateContext, rawValue, ",");
        SubjectManager subjectManager = AuthorizationUtils.getAuthorizationManager();
        if(subjectManager.hasAllPermissions(values)) {
            iElementTagStructureHandler.removeTags();
        } else {
            iElementTagStructureHandler.removeElement();
        }

    }
}
